package com.masterclient.app.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.masterclient.app.App;
import com.masterclient.app.R;
import com.eoner.baselibrary.bean.goods.ProductTeamBean;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.TimeUtil;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者：sean
 * 创建时间：2018/4/4 11:19
 * 功能说明：跑马灯view
 */
public class MarqueeLayout extends ViewFlipper {

    private Context mContext;
    /**
     * 是否开启动画
     */
    private boolean isSetAnimDuration = true;
    /**
     * 时间间隔
     */
    private int interval = 3000;
    /**
     * 动画时间
     */
    private int animDuration = 500;
    private CompositeDisposable composite = new CompositeDisposable();
    public MarqueeLayout(Context context) {
        super(context);
        init(context, null, 0);
    }
    public MarqueeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        mContext = context;
        setFlipInterval(3000);
        Animation animIn = AnimationUtils.loadAnimation(getContext(), R.anim.pop_show);
        animIn.setDuration(500);
        setInAnimation(animIn);
        Animation animOut = AnimationUtils.loadAnimation(getContext(), R.anim.pop_hidden_up);
        animOut.setDuration(500);
        setOutAnimation(animOut);
    }


    /**
     * 设置循环滚动的View数组
     */
    @SuppressLint("CheckResult")
    public void setViews(final List<ProductTeamBean.DataBean.ShTeamListBean> datas) {
        if (datas == null || datas.size() == 0) return;
        int size = datas.size();
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
        if(size <= 1){
            layoutParams.height = ScreenUtils.dp2px(60);
        }else {
            layoutParams.height = ScreenUtils.dp2px(120);
        }
        setLayoutParams(layoutParams);
        for (int i = 0; i < size; i += 2) {
            final int position = i;
            LinearLayout linearLayout = new LinearLayout(mContext);
            linearLayout.setOrientation(LinearLayout.VERTICAL);

            ProductTeamBean.DataBean.ShTeamListBean shTeamListBean1 = datas.get(i);
            //根布局
            RelativeLayout view = (RelativeLayout) View.inflate(mContext, R.layout.item_goods_groupbuy, null);
            ViewHolder holder = new ViewHolder(view);
            App.picasso.load(shTeamListBean1.getSh_headimgurl()).transform(new CircleBorderTransform(0,R.color.transparent)).into(holder.ivUserHead);
            holder.tvUserName.setText(shTeamListBean1.getSh_nick_name());
            holder.tvRemainUser.setText("还差"+shTeamListBean1.getSh_poor_join_num()+"人拼成");
            long amount = (int) (TimeUtil.timeRemain2(shTeamListBean1.getSh_end_at())/1000);
            composite.add(Observable.interval(0,1, TimeUnit.SECONDS,Schedulers.computation())
                    .take(amount).observeOn(AndroidSchedulers.mainThread()).subscribe(new TextConsumer(amount,holder.tvRemainTime)));

            if("1".equals(shTeamListBean1.getSh_is_myself())){//自己已加入
                holder.tvButton.setText("喊人参团");
                holder.tvButton.setBackgroundResource(R.drawable.bg_orange);
                holder.tvButton.setOnClickListener(v -> {
                    if(onButtonClickListener!=null){
                        onButtonClickListener.share(shTeamListBean1.getSh_id());
                    }
                });
            }else {//未加入
                holder.tvButton.setText("去参团");
                holder.tvButton.setBackgroundResource(R.drawable.bg_red);
                holder.tvButton.setOnClickListener(v -> {
                    if(onButtonClickListener!=null){
                        onButtonClickListener.buyNow(shTeamListBean1.getSh_id());
                    }
                });
            }
            linearLayout.addView(view);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
            params.height = ScreenUtils.dp2px(60);
            view.setLayoutParams(params);
            if(position+1<size){
                ProductTeamBean.DataBean.ShTeamListBean shTeamListBean2 = datas.get(i+1);
                RelativeLayout view2 = (RelativeLayout) View.inflate(mContext, R.layout.item_goods_groupbuy, null);
                ViewHolder holder2 = new ViewHolder(view2);
                holder2.vLine.setVisibility(VISIBLE);
                App.picasso.load(shTeamListBean2.getSh_headimgurl()).transform(new CircleBorderTransform(0,R.color.transparent)).into(holder2.ivUserHead);
                holder2.tvUserName.setText(shTeamListBean2.getSh_nick_name());
                holder2.tvRemainUser.setText("还差"+shTeamListBean2.getSh_poor_join_num()+"人拼成");
                holder2.tvRemainTime.setText("剩余"+shTeamListBean2.getSh_end_at());
                long amount2 = (int) (TimeUtil.timeRemain2(shTeamListBean2.getSh_end_at())/1000);
                composite.add(Observable.interval(0,1, TimeUnit.SECONDS,Schedulers.computation())
                        .observeOn(AndroidSchedulers.mainThread()).subscribe(new TextConsumer(amount2,holder2.tvRemainTime)));

                if("1".equals(shTeamListBean1.getSh_is_myself())){//自己已加入
                    holder2.tvButton.setText("喊人参团");
                    holder2.tvButton.setBackgroundResource(R.drawable.bg_orange);
                    holder2.tvButton.setOnClickListener(v -> {
                        if(onButtonClickListener!=null){
                            onButtonClickListener.share(shTeamListBean2.getSh_id());
                        }
                    });
                }else {//未加入
                    holder2.tvButton.setText("去参团");
                    holder2.tvButton.setBackgroundResource(R.drawable.bg_red);
                    holder2.tvButton.setOnClickListener(v -> {
                        if(onButtonClickListener!=null){
                            onButtonClickListener.buyNow(shTeamListBean2.getSh_id());
                        }
                    });
                }
                linearLayout.addView(view2);
                LinearLayout.LayoutParams params2 = (LinearLayout.LayoutParams) view2.getLayoutParams();
                params2.height = ScreenUtils.dp2px(60);
                view2.setLayoutParams(params2);
            }
            addView(linearLayout);
        }
    }

    public interface OnButtonClickListener{
        void share(String team_id);
        void buyNow(String team_id);
    }

    private OnButtonClickListener onButtonClickListener;

    public void setOnButtonClickListener(OnButtonClickListener onButtonClickListener) {
        this.onButtonClickListener = onButtonClickListener;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        composite.clear();
    }

    public boolean isSetAnimDuration() {
        return isSetAnimDuration;
    }

    public void setSetAnimDuration(boolean isSetAnimDuration) {
        this.isSetAnimDuration = isSetAnimDuration;
    }

    public int getInterval() {
        return interval;
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }

    public int getAnimDuration() {
        return animDuration;
    }

    public void setAnimDuration(int animDuration) {
        this.animDuration = animDuration;
    }


    static class ViewHolder {
        @BindView(R.id.iv_user_head)
        ImageView ivUserHead;
        @BindView(R.id.tv_remain_user)
        TextView tvRemainUser;
        @BindView(R.id.tv_remain_time)
        TextView tvRemainTime;
        @BindView(R.id.tv_button)
        TextView tvButton;
        @BindView(R.id.tv_user_name)
                TextView tvUserName;
        @BindView(R.id.v_line)
        View vLine;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

/*    private class TextConsumer implements Consumer<Long>{
        TextView tvRemain;
        long amount;
        public TextConsumer(long amount,TextView tvRemain) {
            this.tvRemain = tvRemain;
            this.amount = amount;
        }
        @Override
        public void accept(Long t) throws Exception {
            String time = TimeUtil.getTimeString(amount-t);
           tvRemain.setText("剩余" + time);
        }
    }*/
}
